package learn_concurrent._3;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class T1 {
	static final Logger logger = LoggerFactory.getLogger(T1.class);

	static Random random = new Random();

	public static void main(String[] args) {
		TicketWindow tw = new TicketWindow(10000);
		List<Integer> selledAmountList = new Vector<>();
		List<Thread> buyers = new ArrayList<>();

		for (int i = 0; i < 2000; i++) {
			Thread t = new Thread(() -> {
				int amount = tw.sell(randomAmount());
				selledAmountList.add(amount);
			});
			buyers.add(t);
			t.start();
		}
		
		for(Thread t : buyers) {
			try {
				t.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		int left = tw.getCount();
		int selled = selledAmountList.stream().mapToInt(i -> i).sum();
		logger.info("Left : {}", left);
		logger.info("Selled : {}", selled);
		logger.info("Total = 10000, Result = {}", left + selled);
	}

	// 1 ~ 5
	private static int randomAmount() {
		return random.nextInt(5) + 1;
	}
}

class TicketWindow {

	private int count;

	public TicketWindow(int count) {
		this.count = count;
	}

	public int getCount() {
		return count;
	}

	public synchronized int sell(int amount) {
		if (count >= amount) {
			count -= amount;
			return amount;
		} else {
			return 0;
		}
	}

}
